package com.gouda.temporary.utils;

import com.gouda.temporary.vo.openwx.AccessToken;
import com.gouda.temporary.vo.openwx.TextMsgBody;
import com.gouda.temporary.vo.openwx.UserInfoWithCode;
import com.gouda.temporary.vo.openwx.WxOwnerInfo;

public class OpenWxUtils {

    private static final String BASE_QY_WEIXIN = "https://qyapi.weixin.qq.com/cgi-bin/";

    /**
     * 获取access_token
     * @return 返回失败,返回null
     */
    public static String getAccessToken() {
        String corpid = ConfigUtils.getCorpID();
        String secret = ConfigUtils.getCorpSecret();
        String url    = BASE_QY_WEIXIN + "gettoken?corpid=" + corpid + "&corpsecret=" + secret;
        String body   = XYHttpUtils.doGet(url);
        if (OpenWxUtils.isBlank(body)) {
            return null;
        }

        AccessToken accessToken = CommonUtils.gsonParseObject(body, AccessToken.class);
        return accessToken == null ? null : accessToken.getAccess_token();
    }

    public static String getJsapiTicket() {
        String corpid = ConfigUtils.getCorpID();
        String secret = ConfigUtils.getCorpSecret();
        String url    = BASE_QY_WEIXIN + "gettoken?corpid=" + corpid + "&corpsecret=" + secret;
        String body   = XYHttpUtils.doGet(url);
        if (OpenWxUtils.isBlank(body)) {
            return null;
        }
        AccessToken accessToken = CommonUtils.gsonParseObject(body, AccessToken.class);
        return accessToken == null ? null : accessToken.getAccess_token();
    }


    public static UserInfoWithCode getUserInfoByCode(String code) {
        String url    = BASE_QY_WEIXIN + "user/getuserinfo?access_token=" + CacheUtils.getCachedAccessToken() + "&code=" + code;
        String body   = XYHttpUtils.doGet(url);
        if (OpenWxUtils.isBlank(body)) {
            return null;
        }
        return CommonUtils.gsonParseObject(body, UserInfoWithCode.class);
    }

    public static void sendTextMsgToUser(TextMsgBody msgBody) {
        String url      = BASE_QY_WEIXIN + "message/send?access_token=" + CacheUtils.getCachedAccessToken();
        String postBody = CommonUtils.gsonToJson(msgBody);
        XYHttpUtils.doPost(url, postBody);
    }


    public static boolean isBlank(String str) {
        return str == null || "".equals(str);
    }

    public static WxOwnerInfo getUserDetailInfo(String userId) {
        String url = BASE_QY_WEIXIN + "user/get?access_token=" + CacheUtils.getCachedAccessToken() + "&userid=" + userId;
        String body = XYHttpUtils.doGet(url);

        return CommonUtils.gsonParseObject(body, WxOwnerInfo.class);
    }
}
